#include <pthread.h>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <fcntl.h>
#include <functional>
#include <unistd.h>
#include "LockGuard.hpp"
#include <mutex>
#include <cstring>

using namespace std;

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void *MasterFunc(void *name)
{
    sleep(3); // 确保所有子线程都去条件下等着了
    cout << "Master 开始工作..." << endl;
    // 主线程进行唤醒
    while (1)
    {
        cout << "Master 唤醒一个线程：" << endl;
        // pthread_cond_signal(&gcond);
        pthread_cond_broadcast(&gcond);
        sleep(1);
    }
    return nullptr;
}
void Create_Master(vector<pthread_t> &pth)
{
    pthread_t id;
    int n = pthread_create(&id, nullptr, MasterFunc, (void *)"main_pthread");
    if (n)
    {
        perror("pthread_create error");
        return;
    }
    cout << "master_thread create success!" << endl;

    pth.emplace_back(id);
}

void *SlaverFunc(void *name)
{
    string sname = static_cast<const char *>(name);
    while (1)
    {
        // 所有线程都访问这份共享资源
        pthread_mutex_lock(&gmutex); // 加锁

        pthread_cond_wait(&gcond, &gmutex);              // 让每个执行到这里的线程都去条件下等待
        cout << "当前被唤醒的线程是：" << sname << endl; // 能执行到这里说明已经从等待队列里出来了

        pthread_mutex_unlock(&gmutex); // 解锁
    }
    return nullptr;
}
void Create_Slaver(vector<pthread_t> &pth, int num = 5)
{

    for (int i = 0; i < num; i++)
    {
        char *name = new char[32];
        sprintf(name, "slaver_pthread%d", i + 1);
        pthread_t id;
        int n = pthread_create(&id, nullptr, SlaverFunc, (void *)name);

        pth.emplace_back(id);
    }
}

void Wait_Thread(vector<pthread_t> &pth)
{
    for (auto &e : pth)
    {
        pthread_join(e, nullptr);
    }
}

int main()
{
    vector<pthread_t> pth;

    Create_Master(pth);

    Create_Slaver(pth);

    Wait_Thread(pth);

    return 0;
}